<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getWordDetail, updateWordDetail } from "@/api/words";

const route = useRoute();
const router = useRouter();
const wordId = route.params.id;

const wordDetail = ref("");
const editContent = ref("");
const loading = ref(false);

const getDetail = async () => {
  try {
    const { data } = await getWordDetail(wordId);
    wordDetail.value = data;
    editContent.value = data.notes || "";
  } catch (error) {
    console.error("获取详情失败:", error);
  } finally {
    closeToast();
  }
};

const saveEdit = async () => {
  if (!editContent.value) {
    showFailToast("内容不可为空哦！");
    return;
  }
  loading.value = true;
  try {
    await updateWordDetail(wordId, {
      id: wordId,
      translation: editContent.value,
    });
    showSuccessToast("保存成功");
    wordDetail.value.notes = editContent.value;
  } catch (error) {
    console.error("保存失败:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getDetail();
});
</script>

<template>
  <van-nav-bar title="单词详情" left-arrow @click-left="router.back()" />

  <div class="word-detail" v-if="wordDetail.word">
    <van-cell-group>
      <van-cell title="单词" :value="wordDetail.word" />
      <van-cell title="发音" :value="wordDetail.pronunciation" />
      <van-cell title="翻译" :value="wordDetail.translation" />
      <van-cell title="状态">
        <template #value>
          <van-tag :color="getStatusColor(wordDetail.status)" plain>
            {{ getStatusText(wordDetail.status) }}
          </van-tag>
        </template>
      </van-cell>
    </van-cell-group>

    <div class="edit-section">
      <van-cell-group>
        <van-cell title="笔记" />
      </van-cell-group>
      <van-field
        v-model="editContent"
        type="textarea"
        placeholder="添加你的笔记..."
        rows="6"
        autosize
        show-word-limit
        maxlength="500"
      />
      <div class="save-btn">
        <van-button type="primary" block :loading="loading" @click="saveEdit">
          保存笔记
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
const getStatusColor = (status) => {
  const colors = {
    0: "#c8eede",
    1: "#96f1cb",
    2: "#54f4b1",
    3: "#22A6F2",
  };
  return colors[status] || "#c8eede";
};

const getStatusText = (status) => {
  const texts = {
    0: "陌生",
    1: "一般",
    2: "不错",
    3: "已会",
  };
  return texts[status] || "陌生";
};
</script>

<style scoped lang="scss">
.word-detail {
  padding: 16px;
}

.edit-section {
  margin-top: 16px;

  .save-btn {
    padding: 16px;
  }
}
</style>
